﻿using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Storage;
using Microsoft.WindowsAzure.Management.Storage.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Microsoft.Cloud.API.Azure.Services
{
    public class StorageService : IDisposable
    {
        private readonly StorageManagementClient storageManagementClient = null;

        public StorageService(string subscriptionId)
        {
            this.storageManagementClient = new StorageManagementClient(ADALService.GetCredential(subscriptionId), ADALService.ServiceManagementUrl);
        }

        public StorageService(SubscriptionCloudCredentials credentials, Uri baseUri)
        {
            this.storageManagementClient = new StorageManagementClient(credentials, baseUri);
        }

        public async Task<OperationStatusResponse> CreateStorageAccountAsync(StorageAccountCreateParameters parameters)
        {
            // Create the Storage Account
            var response = await this.storageManagementClient.StorageAccounts.CreateAsync(parameters);

            return response;
        }

        /// <summary>
        /// check if storage account is available
        /// </summary>
        /// <param name="serviceName"></param>
        /// <returns></returns>
        public async Task<CheckNameAvailabilityResponse> CheckStorageAccountNameAsync(string serviceName)
        {
            var response = await this.storageManagementClient.StorageAccounts.CheckNameAvailabilityAsync(serviceName);

            return response;
        }

        /// <summary>
        /// return all storage accounts
        /// </summary>
        /// <returns></returns>
        public async Task<IList<StorageAccount>> GetStorageAccountListAsync()
        {
            var response = await this.storageManagementClient.StorageAccounts.ListAsync();

            return response.StorageAccounts;
        }

        public void Dispose()
        {
            if (this.storageManagementClient != null)
            {
                this.storageManagementClient.Dispose();
            }
        }
    }
}